'''
Created on Nov 25, 2012

@author: trananh
'''
from KTHDataSet import KTHDataSet
from Item import Item
import csv
import glob
import os

class KTHDataReader(object):
    """
    classdocs
    """
    
    @classmethod
    def load(cls, datadir, dataset=None):
        """
        Reads in the data and return a KTHDataSet object which
        holds all the data items.
        """
        if dataset is None:
            dataset = KTHDataSet()
        if os.path.exists(datadir):
            datafiles = glob.glob(os.path.join(datadir, '*.txt'))
            for datafile in datafiles:
                featureName = os.path.basename(datafile)[:-4]
                print 'Loading feature: ' + featureName
                with open(datafile, 'rb') as f:
                    for row in csv.reader(f):
                        label = row[0].strip(); personid = int(row[1].strip())
                        segmentid = row[2].strip() + '/' + row[3].strip()
                        if dataset.hasItem(label, personid, segmentid):
                            item = dataset.getItem(label, personid, segmentid)
                        else:
                            item = Item(label=label, personid=personid, \
                                        segmentid=segmentid, featureNames=list())
                            dataset.addItem(item)
                        item.addData([float(i) for i in row[4:]])
                        item.attributes['featureNames'].append(featureName)          
            
        return dataset


if __name__ == '__main__':
    # Load pose data
    dataset = KTHDataReader.load('/Users/trananh/Workspace/Python/ua-gesture/data/KTH/ground-truth/pose-features-std')
    dataset = KTHDataReader.load('/Users/trananh/Workspace/Python/ua-gesture/data/KTH/ground-truth/flow-features', dataset)
    
#    # Save to pickle so we don't have to keep reading everytime
#    import pickle
#    datasetFile = "/Users/trananh/Workspace/Python/ua-gesture/data/KTH/ground-truth/KTHdataset.pickle"
#    f = open(datasetFile, 'wb')
#    pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL)
#    f.close()
#    
#    # Load pickle and add to it
#    f = open(datasetFile, 'rb')
#    dataset = pickle.load(f)
#    f.close()
    